package pl.lodz.p.browarex.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import pl.lodz.p.browarex.base.BaseCrudDao;
import pl.lodz.p.browarex.model.Order;
import pl.lodz.p.browarex.model.enums.OrderState;

@Repository
public class OrderDAO extends BaseCrudDao<Order, Long> {

	public OrderDAO(Class<Order> type) {
		super(type);
	}

	public OrderDAO() {
		super(Order.class);
	}

	public Order getBasketOrderForCustomer(Long customerID) {
		Criteria criteria = getSession().createCriteria(type);
		criteria.createAlias("customer", "customer");
		criteria.createAlias("productList", "productList");
		criteria.add(Restrictions.eq("customer.id", customerID));
		criteria.add(Restrictions.eq("orderState", OrderState.BASKET));
		Order proxy = (Order) criteria.uniqueResult();
		Hibernate.initialize(proxy);
		return proxy;
	}

	public Order loadByOrderID(String orderID) {
		Criteria criteria = getSession().createCriteria(type);
		criteria.add(Restrictions.eq("orderID", orderID));
		return (Order) criteria.uniqueResult();
	}

	public List<Order> getOrderForCustomer(Long customerID) {
		Criteria criteria = getSession().createCriteria(type);
		criteria.createAlias("customer", "customer");
		criteria.createAlias("productList", "productList");
		criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		criteria.add(Restrictions.eq("customer.id", customerID));
		criteria.add(Restrictions.not(Restrictions.eq("orderState",
				OrderState.BASKET)));
		return criteria.list();
	}

}
